<template>
  <a-layout class="p-workbench-main">
    <MainHeader @search="searchBoard" />
    <a-layout-content class="p-workbench-main__content">
      <div class="p-workbench-main__content-header">
        <div class="p-workbench-main__content-title">{{ contentTitle }}</div>
        <a-flex
          justify="space-between"
          align="center"
          style="padding-top: 15px"
        >
          <a-menu
            v-model:selectedKeys="currentBoardCategory"
            mode="horizontal"
            :items="items"
            @select="changeBoardCategory"
          />
          <a-flex
            gap="small"
            justify="center"
            align="center"
            style="padding-right: 16px"
            v-show="teamMemberList.length > 0"
          >
            <span style="font-size: 1rem">
              共 {{ teamMemberList.length }} 人
            </span>
            <a-avatar-group
              :max-count="3"
              :max-style="{ color: '#00a1ff', backgroundColor: '#b8e3ff' }"
            >
              <a-avatar
                v-for="(item, index) in teamMemberAvatarList"
                :key="index"
                :src="item"
                :size="40"
              />
            </a-avatar-group>
            <a-button
              v-if="teamStore.myTeamRole === boardRole.Owner"
              type="primary"
              shape="circle"
              size="small"
              @click="
                () =>
                  router.push({
                    name: 'teamSetting',
                    query: { activeTab: '2' },
                  })
              "
              :icon="h(PlusOutlined)"
            />
            <a-tooltip>
              <template #title>
                {{ boardData.isShowPic ? '缩略图展示' : '列表展示' }}
              </template>
              <a-button
                type="text"
                :icon="h(AppstoreOutlined)"
                v-if="boardData.isShowPic"
                @click="() => (boardData.isShowPic = false)"
              />
              <a-button
                type="text"
                :icon="h(MenuOutlined)"
                v-else
                @click="() => (boardData.isShowPic = true)"
              />
            </a-tooltip>
          </a-flex>
        </a-flex>
      </div>
      <div class="p-workbench-main__content-body">
        <a-spin :spinning="spinning">
          <a-empty v-if="boardList.length === 0" style="margin: 150px 0 0 0">
            <template #description>
              <span class="color-grey">{{ boardData.emptyText }}</span>
            </template>
          </a-empty>
          <template v-else>
            <div
              class="p-workbench-main__content-body-card"
              v-if="boardData.isShowPic"
            >
              <Thumbnail
                v-for="item in boardList"
                :key="item.id"
                :board-name="item.name"
                :update-time="item.updateTime"
                :image-src="item.coverUrl"
                :my-role="item.myRole"
                :is-recycle-bin="boardData.isRecycleBin"
                @editBoard="editBoard(item.id)"
                @rename="openEditModal(1, item.id, item.name)"
                @delete="openEditModal(2, item.id, item.name)"
                @details="openEditModal(3, item.id)"
                @recover="openEditModal(4, item.id, item.name)"
                @cleanOut="openEditModal(5, item.id, item.name)"
              />
            </div>
            <div v-else>
              <a-table
                :columns="columns"
                :data-source="boardList"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'name'">
                    <span
                      style="margin-right: 15px; cursor: pointer"
                      @click="editBoard(record.id)"
                    >
                      {{ record.name }}
                    </span>
                    <a-tag
                      v-if="record.myRole === boardRole.Viewer"
                      color="warning"
                    >
                      仅浏览
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <a-dropdown :trigger="['click']" placement="bottomRight">
                      <a-button
                        type="text"
                        :icon="h(EllipsisOutlined)"
                      ></a-button>
                      <template #overlay>
                        <a-menu>
                          <template v-if="record.myRole !== boardRole.Viewer">
                            <template v-if="boardData.isRecycleBin">
                              <a-menu-item
                                @click="
                                  openEditModal(4, record.id, record.name)
                                "
                              >
                                恢复
                              </a-menu-item>
                              <a-menu-item
                                @click="
                                  openEditModal(5, record.id, record.name)
                                "
                              >
                                彻底删除
                              </a-menu-item>
                            </template>
                            <template v-else>
                              <a-menu-item
                                @click="
                                  openEditModal(1, record.id, record.name)
                                "
                              >
                                重命名
                              </a-menu-item>
                              <a-menu-item
                                @click="
                                  openEditModal(2, record.id, record.name)
                                "
                              >
                                删除白板
                              </a-menu-item>
                            </template>
                          </template>
                          <a-menu-item @click="openEditModal(3, record.id)">
                            详细信息
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </template>
                </template>
              </a-table>
            </div>
          </template>
        </a-spin>
      </div>
    </a-layout-content>
  </a-layout>
  <a-modal
    v-model:open="modalData.modalVisible"
    :title="modalData.modalTitle"
    :maskClosable="false"
    centered
    :width="450"
    :body-style="{ paddingTop: '24px' }"
    :mask-style="{ backgroundColor: 'rgba(0, 0, 0, 0.2)' }"
    @cancel="cancelModal"
  >
    <template v-if="modalData.optionType === 1">
      <a-form ref="renameFormRef" :model="modalData" :rules="rules">
        <a-form-item name="boardName">
          <a-input
            v-model:value="modalData.boardName"
            placeholder="输入新的白板名称"
          />
        </a-form-item>
      </a-form>
    </template>
    <template v-else-if="modalData.optionType === 2">
      确认将白板「{{ modalData.boardName }}」移入回收站？
    </template>
    <template v-else-if="modalData.optionType === 3">
      <a-descriptions
        :colon="false"
        :column="1"
        :labelStyle="{ fontSize: '0.9rem', color: '#9a9a9a', width: '5rem' }"
      >
        <a-descriptions-item label="文件名">
          {{ modalData.boardInfo.name }}
        </a-descriptions-item>
        <a-descriptions-item label="拥有者">
          {{ modalData.boardInfo.creator }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ modalData.boardInfo.createTime }}
        </a-descriptions-item>
        <a-descriptions-item label="修改时间">
          {{ modalData.boardInfo.updateTime }}
        </a-descriptions-item>
      </a-descriptions>
    </template>
    <template v-else-if="modalData.optionType === 4">
      确认恢复白板「{{ modalData.boardName }}」？
    </template>
    <template v-else>确认彻底删除白板「{{ modalData.boardName }}」？</template>
    <template #footer>
      <template v-if="modalData.optionType !== 3">
        <a-button @click="cancelModal">取消</a-button>
        <a-button
          type="primary"
          @click="editBoardInfo"
          :loading="modalData.confirmLoading"
        >
          确定
        </a-button>
      </template>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { h, reactive, ref, watchEffect } from 'vue';
import { MenuProps, message } from 'ant-design-vue';
import MainHeader from './header/index.vue';
import { useTeamStore, useBoardStore } from '@/store/index.ts';
import {
  PlusOutlined,
  AppstoreOutlined,
  MenuOutlined,
  EllipsisOutlined,
} from '@ant-design/icons-vue';
import Thumbnail from './Thumbnail.vue';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { Rule } from 'ant-design-vue/es/form';
import { validateBoardName } from '@/utils/FormRules.ts';
import { boardRole } from '@/utils/Const.ts';

const router = useRouter();
const teamStore = useTeamStore();
const boardStore = useBoardStore();
const {
  getBoardDetails,
  renameBoard,
  removeBoard,
  recoverBoard,
  cleanOutBoard,
  setCurrentBoardId,
} = boardStore;
const {
  boardCreateByMe,
  boardCreateByOthers,
  teamBoardList,
  teamMemberAvatarList,
  teamMemberList,
} = storeToRefs(teamStore);
const { getTeamMemberList, getBoardListInTeam } = teamStore;
const props = defineProps({
  selectedSiderMenuItemKey: {
    type: String,
    required: true,
  },
});
// 内容区标题
const contentTitle = ref('团队文件');
// 加载状态
const spinning = ref(false);

// 白板分类
const items = ref<MenuProps['items']>([
  {
    key: 'all',
    label: '全部白板',
    title: '全部白板',
  },
  {
    key: 'create',
    label: '我拥有的',
    title: '我拥有的',
  },
  {
    key: 'others',
    label: '他人拥有的',
    title: '他人拥有的',
  },
]);
// 当前选中白板分类
const currentBoardCategory = ref(['all']);
watchEffect(async () => {
  spinning.value = true;
  if (props.selectedSiderMenuItemKey && teamStore.currentTeamId) {
    boardData.isRecycleBin = props.selectedSiderMenuItemKey !== '团队文件';
    contentTitle.value = props.selectedSiderMenuItemKey;
    await getBoardListInTeam(boardData.isRecycleBin);
    await getTeamMemberList();
    changeBoardCategory({ key: currentBoardCategory.value[0] });
    spinning.value = false;
  }
});
// 选择菜单项
function changeBoardCategory(data: any) {
  boardData.emptyText = '这里没有白板哦~';
  boardList.length = 0;
  switch (data.key) {
    case 'all':
      boardList.push(...teamBoardList.value);
      break;
    case 'create':
      boardList.push(...boardCreateByMe.value);
      break;
    case 'others':
      boardList.push(...boardCreateByOthers.value);
      break;
  }
}

// 白板 数据
const boardData = reactive({
  searchName: '',
  emptyText: '暂无白板数据',
  isShowPic: true, // 指定是否缩略图展示白板数据
  isRecycleBin: false, // 判断是否是回收站
});
const boardList = reactive<Array<any>>([]);
// 列表展示的列数据
const columns = [
  {
    title: '文件名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '拥有者',
    dataIndex: 'ownerName',
    key: 'ownerName',
  },
  {
    title: '最后修改时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
  },
  {
    key: 'action',
  },
];

// TODO: 把所有发送请求的方法全部封装到Store中，统一从Store中解构调用

// 搜索白板
async function searchBoard(searchName: string) {
  boardData.searchName = searchName;
  if (searchName === '') {
    contentTitle.value = props.selectedSiderMenuItemKey;
  } else {
    contentTitle.value = `搜索「${boardData.searchName}」结果`;
  }
  await getBoardListInTeam(boardData.isRecycleBin, boardData.searchName);
  changeBoardCategory({ key: currentBoardCategory.value[0] });
}
// 进入 白板编辑器
function editBoard(boardId: string) {
  if (boardData.isRecycleBin) return;
  setCurrentBoardId(boardId);
  router.push({ path: `/board/${boardId}` });
}

//白板编辑信息对话框 数据
const modalData = reactive({
  boardName: '',
  boardInfo: {
    name: '',
    creator: '',
    createTime: '',
    updateTime: '',
  },
  modalVisible: false,
  modalTitle: '',
  optionType: 0,
  boardId: '', // 被操作的白板 boardId
  confirmLoading: false,
});
// 重命名表单引用
const renameFormRef = ref(null);
// 重命名表单校验规则
const rules: Record<string, Rule[]> = {
  boardName: [{ validator: validateBoardName, trigger: ['blur', 'change'] }],
};
// 操作 白板信息
async function openEditModal(
  option: number,
  boardId: string,
  boardName?: string,
) {
  if (boardName) {
    modalData.boardName = boardName;
  }
  modalData.optionType = option;
  modalData.boardId = boardId;
  modalData.modalVisible = true;
  switch (modalData.optionType) {
    // 重命名
    case 1:
      modalData.modalTitle = '重命名白板';
      break;
    // 删除白板
    case 2:
      modalData.modalTitle = '删除白板';
      break;
    // 详细信息
    case 3:
      modalData.modalTitle = '详细信息';
      const data = await getBoardDetails(modalData.boardId);
      modalData.boardInfo.name = data.name;
      modalData.boardInfo.creator = data.ownerName;
      modalData.boardInfo.createTime = data.createTime;
      modalData.boardInfo.updateTime = data.updateTime;
      break;
    // 恢复白板
    case 4:
      modalData.modalTitle = '恢复白板';
      break;
    // 彻底删除白板
    case 5:
      modalData.modalTitle = '彻底删除白板';
      break;
  }
}
// 确认 操作
async function editBoardInfo() {
  modalData.confirmLoading = true;
  switch (modalData.optionType) {
    // 重命名
    case 1:
      renameFormRef.value
        ?.validateFields(['boardName'])
        .then(async (res: any) => {
          await renameBoard(modalData.boardId, res.boardName);
          await getBoardListInTeam(
            boardData.isRecycleBin,
            boardData.searchName,
          );
          changeBoardCategory({ key: currentBoardCategory.value[0] });
          modalData.modalVisible = false;
          modalData.confirmLoading = false;
        })
        .catch((e: Error) => {
          modalData.confirmLoading = false;
          console.error(e);
        });
      break;
    // 删除白板
    case 2:
      try {
        await removeBoard(modalData.boardId);
        await getBoardListInTeam(boardData.isRecycleBin, boardData.searchName);
        changeBoardCategory({ key: currentBoardCategory.value[0] });
        modalData.modalVisible = false;
        modalData.confirmLoading = false;
        message.info('文件已删除至回收站');
      } catch (e) {
        modalData.confirmLoading = false;
        console.error(e);
      }
      break;
    // 恢复白板
    case 4:
      try {
        await recoverBoard(modalData.boardId);
        await getBoardListInTeam(boardData.isRecycleBin, boardData.searchName);
        changeBoardCategory({ key: currentBoardCategory.value[0] });
        modalData.modalVisible = false;
        modalData.confirmLoading = false;
        message.success('文件已恢复');
      } catch (e) {
        modalData.confirmLoading = false;
        console.error(e);
      }
      break;
    // 彻底删除白板
    case 5:
      try {
        await cleanOutBoard(modalData.boardId);
        await getBoardListInTeam(boardData.isRecycleBin, boardData.searchName);
        changeBoardCategory({ key: currentBoardCategory.value[0] });
        modalData.modalVisible = false;
        modalData.confirmLoading = false;
        message.success('文件已彻底删除');
      } catch (e) {
        modalData.confirmLoading = false;
        console.error(e);
      }
      break;
  }
}
// 取消 操作
function cancelModal() {
  if (modalData.optionType === 1) {
    renameFormRef.value?.clearValidate();
  }
  modalData.modalVisible = false;
}
</script>

<style scoped lang="scss">
.p-workbench-main {
  height: 100%;
  overflow: hidden;
  .p-workbench-main__content {
    width: 100%;
    padding: 0 2rem;
    background-color: #ffffff;
    overflow-y: scroll;
    position: relative;
    .p-workbench-main__content-header {
      padding: 0.8rem 0;
      position: sticky;
      top: 0;
      left: 0;
      z-index: 999;
      background-color: #ffffff;
      .p-workbench-main__content-title {
        padding: 0 16px;
        font-size: 1.5rem;
        font-weight: lighter;
      }
    }
    .p-workbench-main__content-body {
      padding: 10px 16px 25px;
      .p-workbench-main__content-body-card {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
        grid-gap: 24px;
      }
    }
  }
}
.color-grey {
  color: #9a9a9a;
}
</style>
